package cn.iphone.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
/**
 * @author 32999
 */
@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 核心业务方法
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        // 获取请求对象
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        // 获取响应对象
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        // 获取token
        String token = request.getHeader("token");
        // 没有token的就登录失败
        if (!StringUtils.hasLength(token)) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("success","false");
            map.put("message","请先登录");
            response.setContentType("application/json;charset=utf-8");
            String jsonString = JSON.toJSONString(map);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            try {
                response.getWriter().print(jsonString);
            } catch (Exception e) {
                e.printStackTrace();
            }
            RequestContext.getCurrentContext().setSendZuulResponse(false);
        }
        return null;
    }
}
